(function(window) {
	var _guuid = 1;
	function genuuid() {
		return new Date().getTime() + "_" + _guuid++;
	}
	var ctor = function(config) {
		this.container = config.container;
		this.baseUrl = config.baseUrl;
		this.ruleSetId = config.ruleSetId;
		this.ruleGroup = config.ruleGroup;
		this.uuid = genuuid();
	};
	var _proto = ctor.prototype;
	_proto.url = function(u) {
		return this.baseUrl + u;
	};
	_proto.id = function(id) {
		return "#" + this.uuid + id;
	};
	_proto.paint = function() {
		var self = this;
		self.loadLayout(function() {
			self.loadRuleTemplates(self.ruleGroup, function() {
				self.loadRuleSet(self.ruleSetId, function() {

				});
			});
		});
	};
	_proto.loadLayout = function(callback) {
		$(this.container).load(this.url("/loadLayout"), {
			editorId : this.uuid,
			ruleSetId : this.ruleSetId
		}, callback);
	};
	_proto.loadRuleTemplates = function(ruleGroup, callback) {
		var self = this;
		$.ajax({
			type : "post",
			url : this.url("/loadRuleTemplates"),
			data : {
				ruleGroup : ruleGroup
			},
			dataType : "json",
			success : function(options) {
				self.options = options || [];
				
				if (options != null) {
					var optionRegion = self.getOptionRegion();
					// str = "规则列表:"// "+itemno+"
					// var tr_ruletext = $("<tr></tr>");
					// var td_ruletext = $("<th colspan=\"2\"
					// style=\"padding: 0 5px;height: 30px;line-height:
					// 14px;\"></th>").text(str); // 以 jQuery 创建新元素
					// var txt3=document.createElement("p"); // 以 DOM 创建新元素
					// txt3.innerHTML="Text.";
					// tr_ruletext.append(td_ruletext);
					// optionRegion.append(tr_ruletext);
					
					var optionRegion1 = self.getSelectionRegion();
					// str = "规则明细:"// "+itemno+"
					// var tr_ruletext = $("<tr></tr>");
					// var td_ruletext = $("<th colspan=\"2\" style=\"padding: 0
					// 5px;height: 30px;line-height: 14px;\"></th>").text(str);
					// // 以 jQuery 创建新元素
					// // var txt3=document.createElement("p"); // 以 DOM 创建新元素
					// // txt3.innerHTML="Text.";
					// tr_ruletext.append(td_ruletext);
					// optionRegion1.append(tr_ruletext);
					
					for (var i = 0, len = options.length; i < len; i++) {
						self.addOption(options[i]);
					}
				}
				callback();
			}
		});
	};
	_proto.getOptionRegion = function() {
		if ($("#table_ele").length > 0) {
			return $("#table_ele");
		} else {
			var temp = $(this.container).find(this.id("option_region"));
			var table_ele = $("<table id=\"table_ele\" class=\"table-list\" width='100%'></table>");
			temp.append(table_ele);
			return $("#table_ele");
		}
	};
	_proto.getSelectionRegion = function() {
		if ($("#table_rule").length > 0) {
			return $("#table_rule");
		} else {
			var temp = $(this.container).find(this.id("selection_region"));
			var table_rule = $("<table id=\"table_rule\" class=\"table-list\" width='100%'></table>");
			temp.append(table_rule);
			return $("#table_rule");
		}
	};
	_proto.unpickRule = function(ruleId) {
		{
			var checkbox = $(this.id("check" + ruleId));
			checkbox.attr("checked", false);
		}
		var div = $(this.container).find(this.id("sel_" + ruleId));
		var parent_tr=div.closest('tr');//div.parent().parent();
		div.remove();
		parent_tr.remove();
	};
	_proto.pickRule = function(ruleId, ruleParams) {// 这儿的括号对应下面的那个);
		{
			var checkbox = $(this.id("check" + ruleId));
			checkbox.attr("checked", true);
		}
		ruleParams = ruleParams || {};
		var options = this.options;
		var rule = null;
		for (var i = 0, len = options.length; i < len; i++) {
			var option = options[i];
			if (option.id == ruleId) {
				rule = option;
				break;
			}
		}
		if (rule == null) {
			return;
		}
		var defaultEditor = "Text";
		var id = rule.id;
		var display = rule.display;
		var group = rule.group;
		var params = rule.params;
		var segmentsRegExp = /\{[a-zA-Z0-9\._]*\}/;
		function evalJson(s) {
			return eval("(" + s + ")");
		}
		function parse(s) {
			var match = s.match(segmentsRegExp);
			var arr = [];

			if (match != null) {
				var index = match.index;
				var left = s.substring(0, index);
				if (left != "") {
					arr.push(left);
				}
				var exp = match[0];
				var paramName = exp.substring(1, exp.length - 1);
				var editorExp = defaultEditor;
				var param = params[paramName];
				if (param) {
					editorExp = param.editor;
				}
				var editorName = editorExp;
				var editorArgs = [];
				{
					var idx = editorExp.indexOf("[");
					if (idx != -1) {
						editorName = editorExp.substring(0, idx);
						var sargs = editorExp.substring(idx + 1,
								editorExp.length - 1);
						var vargs = sargs.split(",");
						for (var i = 0, len = vargs.length; i < len; i++) {
							try {
								editorArgs.push(evalJson(vargs[i]));
							} catch (e) {
								alert("错误的参数表达式：" + editorExp);
								throw e;
							}
						}
					}
				}
				arr.push({
					name : paramName,
					editor : editorName,
					editorArgs : editorArgs
				});
				var right = s.substring(index + exp.length);
				var rightarr = parse(right);
				arr = arr.concat(rightarr);
			} else {
				arr.push(s);
			}
			return arr;
		}
		var segments = parse(display);
		{
			var region = this.getSelectionRegion();
			var row = document.createElement("div");
			region_td=$("<td style=\"padding: 6px;\"></td>")
			region_tr=$("<tr></tr>");
			region_td.append(row);
			region_tr.append(region_td);
			
			region.append(region_tr);
			row = $(row);
			row.attr("id", this.id("sel_" + id).substring(1));
			{
				var input = document.createElement("input");
				input.type = "hidden";
				input.name = this.id("ruleId").substring(1);
				input.value = id;
				row.append(input);
			}
			for (var i = 0, len = segments.length; i < len; i++) {
				var seg = segments[i];
				if (typeof (seg) == "string") {
					row.append(seg);
				} else {
					var paramId = "P" + genuuid();
					var pname = this.id("NameOf" + paramId).substring(1);
					var pvalue = this.id("ValueOf" + paramId).substring(1);
					{
						var hidden = document.createElement("input");
						hidden.name = this.id("Param" + id).substring(1);
						hidden.type = "hidden";
						hidden.value = paramId;
						row.append(hidden);
					}
					{
						var hidden = document.createElement("input");
						hidden.name = pname;
						hidden.type = "hidden";
						hidden.value = seg.name;
						row.append(hidden);
					}
					{
						var span = document.createElement("span");
						row.append(span);
						span = $(span);
						var editor = seg.editor;
						var editorArgs = seg.editorArgs;
						var widget = RuleWidgetFactory.createWidget(editor,
								pvalue, editorArgs);
						widget.render(span);
						var widgetValue = ruleParams[seg.name];
						if (widgetValue) {
							widget.setValue(widgetValue);
						}
					}
				}
			}
		}
	};
	_proto.addOption = function(option) {
		var id = option.id;
		var display = option.display;
		var group = option.group;
		var params = option.params;
		var self = this;
		var segmentsRegExp = /\{[a-zA-Z0-9\._]*\}/;
		function evalJson(s) {
			return eval("(" + s + ")");
		}
		function parse(s) {
			var match = s.match(segmentsRegExp);
			var arr = [];
			if (match != null) {
				var index = match.index;
				var left = s.substring(0, index);
				if (left != "") {
					arr.push(left);
				}
				var exp = match[0];
				var paramName = exp.substring(1, exp.length - 1);
				var text = paramName;
				var param = params[paramName];
				if (param && param.text) {
					text = param.text;
				}
				arr.push("<u>" + text + "</u>");
				var right = s.substring(index + exp.length);
				var rightarr = parse(right);
				arr = arr.concat(rightarr);
			} else {
				arr.push(s);
			}
			return arr;
		}
		var segments = parse(display);
		{
			var optionRegion = this.getOptionRegion();
			
			var tr_input = document.createElement("tr");
			optionRegion.append(tr_input);
			var row = $(tr_input);
			{
				var checkbox = document.createElement("input");
				checkbox.type = "checkbox";
				$(checkbox).attr("ruleid", id);
				$(checkbox).attr("id", this.id("check" + id).substring(1));
				checkbox.onclick = function() {
					if (this.checked) {// remove
						self.pickRule(id);
					} else {// add
						self.unpickRule(id);
					}
				}
				var td_check = $("<td style=\"padding: 6px;\"></td>");
				td_check.append(checkbox);
				row.append(td_check);
			}
			var strmessage = "";
			for (var i = 0, len = segments.length; i < len; i++) {
				var seg = segments[i];
				strmessage = strmessage + seg;
			}
			var td_message = $("<td style=\"padding: 6px;\"></td>").append(strmessage)
			row.append(td_message);
		}
	};
	_proto.loadRuleSet = function(ruleSetId, callback) {
		var self = this;
		$.ajax(this.url("/loadRuleSet"), {
			data : {
				ruleSetId : ruleSetId
			},
			dataType : "json",
			success : function(ruleSet) {
				if (!ruleSet) {
					return;
				}
				var items = ruleSet.ruleItems;
				if (!items) {
					return;
				}
				for (var i = 0, len = items.length; i < len; i++) {
					var item = items[i];
					var ruleId = item.ruleId;
					self.pickRule(ruleId, item.params);
				}
			}
		});
	}
	window.RuleSetEditor = ctor;
})(window);